package com.yuan.weike.controller;

import com.yuan.weike.common.BaseResponse;
import com.yuan.weike.common.ResultUtils;
import com.yuan.weike.exception.BusinessException;
import com.yuan.weike.exception.ErrorCode;
import com.yuan.weike.model.Task;
import com.yuan.weike.model.TaskAccept;
import com.yuan.weike.model.TaskEvaluation;
import com.yuan.weike.model.TaskWithEmployer;
import com.yuan.weike.model.User;
import com.yuan.weike.model.UserRoleEnum;
import com.yuan.weike.service.TaskAcceptService;
import com.yuan.weike.service.TaskEvaluationService;
import com.yuan.weike.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/task")
public class TaskController {

    @Autowired
    private TaskService taskService;
    
    @Autowired
    private TaskAcceptService taskAcceptService;

    @Autowired
    private TaskEvaluationService taskEvaluationService;

    /**
     * 发布任务
     *
     * @param task 任务对象
     * @return 发布后的任务对象
     */
    @PostMapping("/publish")
    public BaseResponse<Task> publishTask(@RequestBody Task task, HttpServletRequest request) {
        // 检查任务信息是否完整
        if (task.getTitle() == null || task.getTitle().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "任务标题不能为空");
        }
        if (task.getDescription() == null || task.getDescription().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "任务描述不能为空");
        }
        if (task.getBudget() == null || task.getBudget().compareTo(java.math.BigDecimal.ZERO) <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "预算必须大于0");
        }

        // 从session中获取当前用户ID作为雇主ID
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        task.setEmployerId(loginUser.getUserId());

        Task publishedTask = taskService.publishTask(task);
        return ResultUtils.success(publishedTask);
    }

    /**
     * 获取所有未关闭的任务（状态不等于3）
     *
     * @return 任务列表
     */
    @GetMapping("/all")
    public BaseResponse<List<TaskWithEmployer>> getAllTasks() {
        List<TaskWithEmployer> tasks = taskService.getAllTasksWithEmployer();
        return ResultUtils.success(tasks);
    }

    /**
     * 获取所有任务（包括已关闭的任务）- 管理员专用
     *
     * @param request HTTP请求
     * @return 任务列表
     */
    @GetMapping("/all-with-closed")
    public BaseResponse<List<TaskWithEmployer>> getAllTasksWithClosed(HttpServletRequest request) {
        // 检查是否为管理员
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        
        // 检查是否为管理员
        if (!Integer.valueOf(UserRoleEnum.ADMIN.getValue()).equals(loginUser.getRole())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限操作");
        }
        
        List<TaskWithEmployer> tasks = taskService.getAllTasksWithEmployerIncludeClosed();
        return ResultUtils.success(tasks);
    }

    /**
     * 根据ID获取任务详情
     *
     * @param taskId 任务ID
     * @return 任务对象
     */
    @GetMapping("/detail/{taskId}")
    public BaseResponse<TaskWithEmployer> getTaskDetail(@PathVariable Long taskId) {
        if (taskId == null || taskId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "任务ID无效");
        }
        
        TaskWithEmployer task = taskService.getTaskByIdWithEmployer(taskId);
        if (task == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "任务不存在");
        }
        
        return ResultUtils.success(task);
    }

    /**
     * 根据ID获取任务详情及评价
     *
     * @param taskId 任务ID
     * @return 任务对象及评价
     */
    @GetMapping("/detail-with-evaluation/{taskId}")
    public BaseResponse<TaskDetailWithEvaluation> getTaskDetailWithEvaluation(@PathVariable Long taskId) {
        if (taskId == null || taskId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "任务ID无效");
        }
        
        TaskWithEmployer task = taskService.getTaskByIdWithEmployer(taskId);
        if (task == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "任务不存在");
        }
        
        TaskEvaluation evaluation = taskEvaluationService.getTaskEvaluationByTaskId(taskId);
        
        TaskDetailWithEvaluation result = new TaskDetailWithEvaluation();
        result.setTask(task);
        result.setEvaluation(evaluation);
        
        return ResultUtils.success(result);
    }

    /**
     * 根据雇主ID获取任务列表（我发布的任务）
     *
     * @param request HTTP请求
     * @return 任务列表
     */
    @GetMapping("/my")
    public BaseResponse<List<Task>> getMyTasks(HttpServletRequest request) {
        // 从session中获取当前用户ID
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        List<Task> tasks = taskService.getTasksByEmployerId(loginUser.getUserId());
        return ResultUtils.success(tasks);
    }

    /**
     * 根据接取者ID获取任务列表（我接取的任务）
     *
     * @param request HTTP请求
     * @return 任务列表
     */
    @GetMapping("/accepted")
    public BaseResponse<List<TaskWithEmployer>> getAcceptedTasks(HttpServletRequest request) {
        // 从session中获取当前用户ID
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        // 获取用户接取的任务列表
        List<TaskAccept> taskAccepts = taskAcceptService.getTaskAcceptsByWitkeyId(loginUser.getUserId());
        
        // 获取任务ID列表
        List<Long> taskIds = taskAccepts.stream().map(TaskAccept::getTaskId).toList();
        
        // 根据任务ID列表获取任务详情
        List<TaskWithEmployer> tasks = taskService.getTasksByIds(taskIds);
        
        return ResultUtils.success(tasks);
    }

    /**
     * 更新任务
     *
     * @param task 任务对象
     * @return 更新后的任务对象
     */
    @PutMapping("/update")
    public BaseResponse<Task> updateTask(@RequestBody Task task, HttpServletRequest request) {
        // 检查任务ID是否有效
        if (task.getTaskId() == null || task.getTaskId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "任务ID无效");
        }

        // 检查任务信息是否完整
        if (task.getTitle() == null || task.getTitle().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "任务标题不能为空");
        }
        if (task.getDescription() == null || task.getDescription().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "任务描述不能为空");
        }
        if (task.getBudget() == null || task.getBudget().compareTo(java.math.BigDecimal.ZERO) <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "预算必须大于0");
        }

        // 从session中获取当前用户
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        // 检查任务是否属于当前用户或是否为管理员
        Task existingTask = taskService.getTaskById(task.getTaskId());
        if (existingTask == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "任务不存在");
        }
        boolean isAdmin = Integer.valueOf(UserRoleEnum.ADMIN.getValue()).equals(loginUser.getRole());
        if (!existingTask.getEmployerId().equals(loginUser.getUserId()) && !isAdmin) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限操作该任务");
        }

        Task updatedTask = taskService.updateTask(task);
        return ResultUtils.success(updatedTask);
    }

    /**
     * 删除任务
     *
     * @param taskId 任务ID
     * @param request HTTP请求
     * @return 是否删除成功
     */
    @DeleteMapping("/delete/{taskId}")
    public BaseResponse<Boolean> deleteTask(@PathVariable Long taskId, HttpServletRequest request) {
        // 检查任务ID是否有效
        if (taskId == null || taskId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "任务ID无效");
        }

        // 从session中获取当前用户
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        // 检查任务是否属于当前用户或是否为管理员
        Task existingTask = taskService.getTaskById(taskId);
        if (existingTask == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "任务不存在");
        }
        boolean isAdmin = Integer.valueOf(UserRoleEnum.ADMIN.getValue()).equals(loginUser.getRole());
        if (!existingTask.getEmployerId().equals(loginUser.getUserId()) && !isAdmin) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限操作该任务");
        }

        boolean result = taskService.deleteTask(taskId);
        return ResultUtils.success(result);
    }

    /**
     * 关闭任务
     *
     * @param taskId 任务ID
     * @param request HTTP请求
     * @return 关闭后的任务对象
     */
    @PutMapping("/close/{taskId}")
    public BaseResponse<Task> closeTask(@PathVariable Long taskId, HttpServletRequest request) {
        // 检查任务ID是否有效
        if (taskId == null || taskId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "任务ID无效");
        }

        // 从session中获取当前用户
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        // 检查任务是否属于当前用户或是否为管理员
        Task existingTask = taskService.getTaskById(taskId);
        if (existingTask == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "任务不存在");
        }
        boolean isAdmin = Integer.valueOf(UserRoleEnum.ADMIN.getValue()).equals(loginUser.getRole());
        if (!existingTask.getEmployerId().equals(loginUser.getUserId()) && !isAdmin) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限操作该任务");
        }

        Task closedTask = taskService.closeTask(taskId);
        return ResultUtils.success(closedTask);
    }

    /**
     * 接取任务
     *
     * @param taskId 任务ID
     * @param request HTTP请求
     * @return 是否接取成功
     */
    @PostMapping("/accept/{taskId}")
    public BaseResponse<Boolean> acceptTask(@PathVariable Long taskId, HttpServletRequest request) {
        // 检查任务ID是否有效
        if (taskId == null || taskId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "任务ID无效");
        }

        // 从session中获取当前用户（接取者）
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        // 检查任务是否存在
        Task task = taskService.getTaskById(taskId);
        if (task == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "任务不存在");
        }

        // 检查任务是否已经被接取
        TaskAccept existingTaskAccept = taskAcceptService.getTaskAcceptByTaskIdAndWitkeyId(taskId, loginUser.getUserId());
        if (existingTaskAccept != null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "任务已被接取");
        }

        // 创建任务承接记录
        TaskAccept taskAccept = new TaskAccept();
        taskAccept.setTaskId(taskId);
        taskAccept.setWitkeyId(loginUser.getUserId());
        taskAccept.setAcceptTime(new Date());
        taskAccept.setDeliveryStatus(0); // 未交付
        taskAcceptService.addTaskAccept(taskAccept);

        // 更新任务状态为进行中，并设置接取者ID
        task.setStatus(1); // 进行中
        task.setEmployeeId(loginUser.getUserId()); // 设置任务接取者
        taskService.updateTask(task);

        return ResultUtils.success(true);
    }

    /**
     * 放弃任务
     *
     * @param taskId 任务ID
     * @param request HTTP请求
     * @return 是否放弃成功
     */
    @PostMapping("/release/{taskId}")
    public BaseResponse<Boolean> releaseTask(@PathVariable Long taskId, HttpServletRequest request) {
        // 检查任务ID是否有效
        if (taskId == null || taskId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "任务ID无效");
        }

        // 从session中获取当前用户（接取者）
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        // 检查任务是否存在
        Task task = taskService.getTaskById(taskId);
        if (task == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "任务不存在");
        }

        // 检查任务是否属于当前用户
        TaskAccept taskAccept = taskAcceptService.getTaskAcceptByTaskIdAndWitkeyId(taskId, loginUser.getUserId());
        if (taskAccept == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限操作该任务");
        }

        // 检查任务状态是否为进行中
        if (task.getStatus() != 1) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "任务状态不正确，无法放弃");
        }

        // 删除任务承接记录
        taskAcceptService.deleteTaskAccept(taskAccept.getAcceptId());

        // 更新任务状态为待接取，并清空接取者ID
        task.setStatus(0); // 待接取
        task.setEmployeeId(null); // 清空任务接取者
        taskService.updateTask(task);

        return ResultUtils.success(true);
    }

    /**
     * 完成任务
     *
     * @param taskId 任务ID
     * @param request HTTP请求
     * @return 是否完成成功
     */
    @PostMapping("/complete/{taskId}")
    public BaseResponse<Boolean> completeTask(@PathVariable Long taskId, HttpServletRequest request) {
        // 检查任务ID是否有效
        if (taskId == null || taskId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "任务ID无效");
        }

        // 从session中获取当前用户（接取者）
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        // 检查任务是否存在
        Task task = taskService.getTaskById(taskId);
        if (task == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "任务不存在");
        }

        // 检查用户是否接取了该任务
        TaskAccept taskAccept = taskAcceptService.getTaskAcceptByTaskIdAndWitkeyId(taskId, loginUser.getUserId());
        if (taskAccept == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限操作该任务");
        }

        // 检查任务状态是否为进行中
        if (task.getStatus() != 1) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "任务状态不正确，无法完成");
        }

        // 更新任务状态为已完成
        task.setStatus(2); // 已完成
        taskService.updateTask(task);

        return ResultUtils.success(true);
    }

    /**
     * 任务详情与评价的组合类
     */
    public static class TaskDetailWithEvaluation {
        private TaskWithEmployer task;
        private TaskEvaluation evaluation;

        public TaskWithEmployer getTask() {
            return task;
        }

        public void setTask(TaskWithEmployer task) {
            this.task = task;
        }

        public TaskEvaluation getEvaluation() {
            return evaluation;
        }

        public void setEvaluation(TaskEvaluation evaluation) {
            this.evaluation = evaluation;
        }
    }
}